import { toRaw } from "vue"
/**
 * 屏幕平面的z轴为0
 * 左上角为(x: 0, y: 0)
 * 中点为(x: 50, y: 50)
 * 其中，x,y单位为%，z无单位
 * coor的z为0时为无透视
*/
const TEMPLATE = {
  x: 0,
  y: 0,
  z: 0,
  scale: 1,
  blur: 0,
  translateX: 0,
  translateY: 0,
}
export class Coordinate {
  constructor( x = 50, y = 50, z = 100, width, height ) {
    this.width = width
    this.height = height
    this.coor = { x, y, z }
    this.targets = new Map()
  }
  setPosition( target, x = 0, y = 0, z = 0 ) {
    let origin = TEMPLATE
    if (this.targets.has(target)) {
      origin = this.targets.get(target)
    }
    const { scale, blur } = this.computeScaleAndBlur(z)
    const { translateX, translateY } = this.computeTranslate(x, y, z)
    this.targets.set(target, {
      ...origin,
      scale, blur,
      translateX, translateY,
      x, y, z
    })
  }
  // 计算倍数和模糊
  computeScaleAndBlur(z) {
    if (this.coor.z === 0) return { scale: 1, blur: 1 }
    else if (this.coor.z < z) return { scale: 0.05, blur: 1 }
    else return { scale: (this.coor.z - z) / this.coor.z, blur: 0 }
  }
  // 计算偏移
  computeTranslate(x, y, z) {
    const xo = this.coor.x
    const yo = this.coor.y
    if (this.coor.z === 0) return { translateX: 0, translateY: 0 }
    else if (this.coor.z < z) return { translateX: xo - x, translateY: yo - y }
    else return { translateX: (xo - x) * z / this.coor.z, translateY: (yo - y) * z / this.coor.z }
  }
  getStyle(target) {
    const that = this
    if (target && this.targets.has(target)) {
      _getStyle(target)
    } else {
      this.targets.forEach((_, key) => _getStyle(key))
    }
    function _getStyle(target) {
      const props = that.targets.get(target)
      const {
        x,
        y,
        z,
        scale,
        blur,
        translateX,
        translateY,
      } = props
      target.style.transform = `translate(${that.width*(x+translateX) + 200}px, ${that.height*(y+translateY) - 100}px) scale(${scale})`
      target.style.filter = `blur(${blur})`
    }
  }
}